<template>
  <view class="container px-2 py-1">
    <!-- 真实姓名输入行 -->
    <view class="form-row py-1">
      <view class="label">
        <text class="colorprice">*</text>
        <text class="color666  font30">真实姓名：</text>
      </view>
      <input
          v-model="form.real_name"
          @input="validateForm"
          placeholder="请输入真实姓名"
          confirm-type="done"
          maxlength="20"
      />
    </view>

    <!-- 身份证号输入行 -->
    <view class="form-row py-1">
      <view class="label">
        <text class="colorprice">*</text>
        <text class="color666  font30">身份证号：</text>
      </view>
      <input
          type="idcard"
          v-model="form.id_card"
          @input="validateForm"
          placeholder="请输入身份证号"
          confirm-type="done"
          maxlength="18"
      />
    </view>

    <!-- 身份证照片拍摄 -->
    <view class="photo-section py-4">
      <text class="section-title font30 pb-3">
        <text class="colorprice">*</text>
        身份证照片：
      </text>
      <view class="photo-grid mt-2">
        <view class="photo-item rounded20 colorFC6127">
          <uni-file-picker
              v-model="cardImageList"
              :auto-upload="false"
              :limit="1"
              :source-type="['album', 'camera']"
              @select="handleImageSelect($event,'id_card_front','cardImageList')"
              @delete="handleImageDelete($event,'id_card_front','cardImageList')"
              file-mediatype="image">
            <view style="width: 100%; height: 100%;">
              <image
                  v-if="form.id_card_front"
                  :src="form.id_card_front"
                  mode="aspectFill"
                  style="width: 100%; height: 100%;"
              />
              <template v-else>
                <view class="placeholder" style="width: 100%; height: 100%;">
                  <text class="color666 text">身份证正面</text>
                  <image
                      mode="widthFix"
                      style="width: 100rpx"
                      class="img"
                      src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/zheng.jpg"></image>
                </view>
              </template>
            </view>
          </uni-file-picker>
        </view>
        <view class="photo-item rounded20 colorFC6127">
          <uni-file-picker
              v-model="cardBackImageList"
              :auto-upload="false"
              :limit="1"
              :source-type="['album', 'camera']"
              @select="handleImageSelect($event,'id_card_back','cardBackImageList')"
              @delete="handleImageDelete($event,'id_card_back','cardBackImageList')"
              file-mediatype="image">
            <view style="width: 100%; height: 100%;">
              <image
                  v-if="form.id_card_back"
                  :src="form.id_card_back"
                  mode="aspectFill"
                  style="width: 100%; height: 100%;"
              />
              <template v-else>
                <view class="placeholder" style="width: 100%; height: 100%;">
                  <text class="color666 text">身份证背面</text>
                  <image
                      mode="widthFix"
                      style="width: 100rpx"
                      class="img"
                      src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/ch/fan.jpg"></image>
                </view>
              </template>
            </view>
          </uni-file-picker>
        </view>
      </view>
    </view>

    <!-- 温馨提示 -->
    <view class="photo-section py-2">
      <text class="section-title font30 pb-1">温馨提示：</text>
      <view class="tips-list">
        <text class="tip-item">1. 实名信息需保证真实有效，若存在虚假信息将封禁账号。</text>
        <text class="tip-item">2. 实名一旦认证，将不可更改，且不可修改性别。</text>
        <text class="tip-item">3. 实名信息将影响结算，请保证身份一致真实有效。</text>
        <text class="tip-item">4. 违规用户的实名信息将禁止再次认证使用。</text>
        <text class="tip-item">5. 完成实名认证后，将奖励1000热度包，可自行为品类增加热度。</text>
        <text class="tip-item">6. 为保证实名有效性，仅允许(18~40)周岁进行认证。</text>
        <text class="tip-item">7. 实名信息将通过接口自动审核，若非出现严重违规情况，人工不介入查看。</text>
      </view>
    </view>

    <!-- 提交按钮 -->
    <button
        class="submit-btn font30"
        @click="handleSubmit"
    >
      提交认证
    </button>
  </view>
</template>

<script>
import {fileApi} from '@/http/fileApi.js';
import store from '@/store/index.js';

export default {
  data() {
    return {
      form: {
        real_name: '',
        id_card: '',
        id_card_front: '',
        id_card_back: ''
      },
      cardImageList: [],
      cardBackImageList: [],
      formValid: false
    }
  },

  onLoad() {
    // 页面加载时初始化表单验证
    this.$nextTick(() => {
      this.validateForm();
    });
  },

  methods: {
    // 验证真实姓名
    validateName() {
      const name = this.form.real_name?.trim() || '';
      // 验证姓名长度和是否为中文
      return name.length >= 2 && name.length <= 20 && /^[\u4e00-\u9fa5]+$/.test(name);
    },

    // 验证身份证号
    validateIdCard() {
      const idCard = this.form.id_card?.trim() || '';
      const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
      return reg.test(idCard) && this.validateIdCardAge(idCard);
    },

    // 验证身份证年龄范围(18-40岁)
    validateIdCardAge(idCard) {
      // 确保证身份证号长度正确
      if (idCard.length !== 18) return false;

      const year = parseInt(idCard.substring(6, 10));
      const month = parseInt(idCard.substring(10, 12));
      const day = parseInt(idCard.substring(12, 14));

      // 验证日期有效性
      const date = new Date(year, month - 1, day);
      if (
          date.getFullYear() !== year ||
          date.getMonth() !== month - 1 ||
          date.getDate() !== day
      ) {
        return false;
      }

      const now = new Date();

      // 计算准确年龄
      let age = now.getFullYear() - date.getFullYear();
      const monthDiff = now.getMonth() - date.getMonth();

      // 如果当前月份小于出生月份，或者月份相同但当前日期小于出生日期，则年龄减1
      if (monthDiff < 0 || (monthDiff === 0 && now.getDate() < date.getDate())) {
        age--;
      }

      return age >= 18 && age <= 40;
    },

    async handleImageSelect(event, side, img) {
      try {
        uni.showLoading({
          title: '上传中...'
        });

        const files = event.tempFiles;
        if (files && files.length > 0) {
          const filePath = files[0].path;

          // 上传图片
          const res = await fileApi.upload(filePath);

          uni.hideLoading();

          if (res && res.data) {
            this.form[side] = res.data;
            // 更新 skillImageList 以显示已上传的图片
            this[img] = [{url: res.data}];
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            });
          }
        }
      } catch (err) {
        uni.hideLoading();
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        });
        console.error('上传失败:', err);
      }
    },
    // 处理图片删除事件
    handleImageDelete(e, side, img) {
      this.form[side] = '';
      this[img] = [];
    },

    // 表单验证方法
    validateForm() {
      // 检查真实姓名
      if (!this.form.real_name) {
        return false;
      }

      if (!this.validateName()) {
        return false;
      }

      // 检查身份证号
      if (!this.form.id_card) {
        return false;
      }

      if (!this.validateIdCard()) {
        return false;
      }

      // 检查必要图片是否已上传
      if (!this.form.id_card_front) {
        return false;
      }

      if (!this.form.id_card_back) {
        return false;
      }

      // 所有验证通过
      this.formValid = true;
      return true;
    },


    // 提交处理
    async handleSubmit() {
      // 先验证表单
      const isValid = this.validateForm();

      if (!isValid) {
        // 提供具体的错误提示
        if (!this.form.real_name) {
          uni.showToast({
            title: '请输入真实姓名',
            icon: 'none'
          });
          return;
        }

        if (!this.validateName()) {
          uni.showToast({
            title: '姓名应为2-20个中文字符',
            icon: 'none'
          });
          return;
        }

        if (!this.form.id_card) {
          uni.showToast({
            title: '请输入身份证号',
            icon: 'none'
          });
          return;
        }

        if (!this.validateIdCard()) {
          uni.showToast({
            title: '请输入正确的身份证号',
            icon: 'none'
          });
          return;
        }

        if (!this.form.id_card_front) {
          uni.showToast({
            title: '请上传身份证正面照片',
            icon: 'none'
          });
          return;
        }

        if (!this.form.id_card_back) {
          uni.showToast({
            title: '请上传身份证背面照片',
            icon: 'none'
          });
          return;
        }

        return;
      }

      uni.showLoading({
        title: '提交中...',
        mask: true
      });

      try {
        // 提交到服务器
        await fileApi.realName(this.form);

        // 成功后更新全局状态
        store.commit('setUserInfo', {
          real_name: this.form.real_name,
          id_card: this.form.id_card
        })
        uni.showToast({
          title: '认证成功',
          icon: 'success'
        });

        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } catch (err) {
        uni.showToast({
          title: err.message,
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    }
  },

  watch: {
    'form.real_name': 'validateForm',
    'form.id_card': 'validateForm',
    'form.id_card_front': 'validateForm',
    'form.id_card_back': 'validateForm'
  }
}
</script>

<style scoped>
.form-row {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #eee;
}

.label {
  width: 180rpx;
}

input {
  flex: 1;
  height: 80rpx;
  font-size: 28rpx;
}

.section-title {
  display: block;
}

.photo-grid {
  display: flex;
  justify-content: space-between;
}

.photo-item {
  width: 48%;
  height: 240rpx;
  border: 1rpx dashed #ccc;
  overflow: hidden;
}


.placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #999;
  position: relative;
  background-color: rgba(0, 0, 0, .1);
}

.placeholder .img {
  width: 70%;
  position: absolute;
  z-index: -1;
}

.placeholder .text {
  position: absolute;
  z-index: 2;
  bottom: 5px;
}

.submit-btn {
  background: #598dfc;
  color: white;
}

.submit-btn[disabled] {
  opacity: 0.6;
}

.color598dfc {
  color: #598dfc;
}

.colorFC6127 {
  border: 1rpx dashed #FC6127;
}

.placeholder .imgIcon {
  width: 40%;
}

input {
  flex: 1;
  height: 80rpx;
  font-size: 28rpx;
}

.photo-grid {
  display: flex;
  justify-content: space-between;
}

.photo-item {
  width: 48%;
  height: 180rpx;
  overflow: hidden;
}

.photo-item ::v-deep .uni-file-picker__container {
  width: 100%;
  height: 180rpx;
  margin: 0;
}

.photo-item ::v-deep .uni-file-picker__files {
  width: 100%;
  height: 100%;
}

.photo-item ::v-deep .file-picker__box {
  width: 100% !important;
  height: 100% !important;
  display: flex;
  align-items: center;
  justify-content: center;
}


.photo-item ::v-deep .file-picker__box-content {
  display: flex;
  align-items: center;
  justify-content: center;
  border: none !important;
  margin: 0 !important;
}

.placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #FC6127;
}

.colorFC6127 {
  border: 1rpx dashed #FC6127;
}

.placeholder .img {
  width: 30%;
}

.colorprice {
  color: #f56c22;
  margin-right: 6rpx;
}

.tips-list {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
}

.tip-item {
  display: block;
  font-size: 22rpx;
  color: #666;
  margin-bottom: 10rpx;
  line-height: 1.5;
}

.tip-item:last-child {
  margin-bottom: 0;
}

.submit-btn {
  background: linear-gradient(90deg, #598dfc, #3a66c7);
  color: white;
  border: none;
  border-radius: 50rpx;
  height: 90rpx;
}
</style>